#!/usr/bin/env bash

# Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

srcdir=${pkg}
cd ${srcdir} || exit 1

configure=
if [ ${impure} -eq 1 ]; then
    configure="./configure.gnu"
else
    configure="./Configure -de"
fi

extra_args=()
if [ ${impure} -eq 0 ]; then
    extra_args+=(-Dcc=${CC})
    extra_args+=(-Dtargetarch=${arch}-linux)
fi

if [ ${host_toolchain} -eq 1 ]; then
    extra_args+=(-Dhostperl=/usr/bin/perl)

    export NATIVE_TOOL_DIR=/usr/bin/
fi

if [ ${host_toolchain} -eq 1 ] && [ "${arch}" = "x86_64" ]; then
    extra_args+=(-Dintsize=4)
    extra_args+=(-Dlongsize=8)
    extra_args+=(-Dshortsize=2)
    extra_args+=(-Dlonglongsize=8)
    extra_args+=(-Ddoublekind=3)
    extra_args+=(-Ddoublesize=8)
    extra_args+=(-Dlongdblkind=3)
    extra_args+=(-Dlongdblsize=16)
    extra_args+=(-Dptrsize=8)

    extra_args+=(-DsPRId64='"ld"')
    extra_args+=(-DsPRIi64='"li"')
    extra_args+=(-DsPRIu64='"lu"')
    extra_args+=(-DsPRIo64='"lo"')
    extra_args+=(-DsPRIx64='"lx"')
    extra_args+=(-DsPRIXU64='"lX"')
fi

if [ -n "${toolchain_glibc_version}" ]; then
    export GLIBC_VERSION=${toolchain_glibc_version}
fi

${configure} \
    -Dprefix=/usr \
    -Dman1dir=/usr/share/man/man1 \
    -Dman3dir=/usr/share/man/man3 \
    ${extra_args[@]} \
    || exit 1
make -j ${MAX_JOBS}
